#!/usr/bin/python
# -*- coding: UTF-8 -*-

import paramiko, datetime, os, logging

#scp = paramiko.Transport(('192.168.0.232', 22))
#scp.connect(username='root', password='diyi20170411')
#sftp = paramiko.SFTPClient.from_transport(scp)
#sftp.get('/var/opt/gitlab/backups/1491814034_2017_04_10_gitlab_backup.tar', '1491814034_2017_04_10_gitlab_backup.tar')
#scp.close()

local_dir = 'backups'
remote_dir = '/var/opt/gitlab/backups'
server = '192.168.0.232'
port = 22
username = 'root'
password = 'diyi20170411'

try:
	scp = paramiko.Transport((server, port))
	scp.connect(username=username, password=password)
	sftp = paramiko.SFTPClient.from_transport(scp)

	logging.basicConfig(filename='bak.log', level=logging.INFO)

	logging.info('----------------------------------------------------------')
	logging.info('Beginning backup gitlab from %s at %s' % (server, datetime.datetime.now()))
	logging.info(' ')

	files = sftp.listdir(remote_dir)

	logging.info('---------------------------------------------------- files')
	index = 0
	for file in files:
		remote_file = '%s/%s' % (remote_dir, file)
		local_file = os.path.join(local_dir, file)

		if os.path.exists(local_file):
			#print('>>> File Exist: ', local_file)
			#print('----------------------------------------------------------')
			continue

		index += 1
		logging.info('[%s] Downloading File: %s' % (index, remote_file))
		#logging.info('Local File: %s ' % (local_file))
		sftp.get(remote_file, local_file)
	logging.info('---------------------------------------------------- files')

	scp.close()

	logging.info(' ')
	logging.info('Backup Done at %s' %(datetime.datetime.now()))
	logging.info('----------------------------------------------------------')
	logging.info('<<<   END                  END                  END   >>>')
except Exception:
	logging.info("connect error!")
